# -*- coding: utf-8 -*-
"""
    author: Ye
    date: 2021/1/28 13:49 
"""
from models.user import User, UserExtend
from marshmallow import fields,Schema,validates
from marshmallow_sqlalchemy.schema import SQLAlchemyAutoSchema,auto_field,ModelSchema
from marshmallow.exceptions import ValidationError


class UserSchema(ModelSchema):
    password = fields.String()

    class Meta:
        model = User
    #
    # def validate(self, data, *, session=None, **kwargs):
    #     # print(data)
    #     password = data.pop('password')
    #     data['_password_hash_'] = generate_password_hash(password)
    #     return data

    @validates('username')
    def validate_username(self,username,**kwargs):
        if User.query.filter_by(username=username).first():
            raise ValidationError(message='用户名已存在')


class UserExtendSchema(SQLAlchemyAutoSchema):
    user = fields.Nested(User)

    class Meta:
        model = UserExtend
